While BFS explored layer-by-layer, DFS takes a different approach: it goes as deep as possible down one path before turning back.
- The core strategy is to aggressively go deep along a single branch, exploring as far as it can.
- When it hits a dead end (a node with no unvisited neighbors), it backtracks to the previous node to try a different path.
- This depth-first exploration is excellent for uncovering structural properties of a graph, like cycles, connectivity, and providing a basis for topological sorting.
- This "last-in, first-out" behavior is naturally implemented using a stack or, more elegantly, through recursion (which uses the call stack).
Formal Definition: Backtracking
Backtracking is the process of returning from a vertex after having explored all of its unvisited neighbors. It is a fundamental step in depth-first exploration, allowing the algorithm to explore alternative paths from a previous vertex.